package com.fx.zmlzml.controller;

import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcMemory;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcMemoryService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑内存条 Controller
 * 提供RESTful API接口，用于操作电脑内存条数据
 */
@RestController
@RequestMapping("/api/memory")
@Tag(name = "电脑内存条管理", description = "提供电脑内存条的CRUD操作及相关查询功能")
public class PcMemoryController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcMemoryController.class);
    
    @Autowired
    private PcMemoryService pcMemoryService;

    /**
     * 分页获取电脑主板列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取电脑主板列表", description = "分页查询系统中的电脑主板信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcMemory>> getPcMemoryByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑内存条列表请求，页码：{}，每页条数：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum <= 0 || pageSize <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.page_num") + "，" + 
                        MessageUtils.getMessage("common.validation.page_size"));
            }

            // 使用PageHelper进行分页
            PageHelper.startPage(pageNum, pageSize);
            List<PcMemory> list = pcMemoryService.list();
            PageInfo<PcMemory> pageInfo = new PageInfo<>(list);

            logger.debug("分页查询电脑内存条列表成功，总条数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "memory.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("分页查询电脑内存条列表异常，页码：{}，每页条数：{}", pageNum, pageSize, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_QUERY_FAILED.getCode(),
                    "memory.query.fail", null);
        }
    }

    /**
     * 根据ID获取电脑内存条信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取电脑内存条信息", description = "根据主键ID查询电脑内存条的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "找不到记录", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcMemory> getPcMemoryById(
            @Parameter(description = "电脑内存条ID", required = true) @PathVariable("id") Long id) {
        logger.info("根据ID查询电脑内存条信息请求，ID：{}", id);
        try {
            PcMemory pcMemory = pcMemoryService.getById(id);
            if (pcMemory == null) {
                logger.warn("根据ID查询电脑内存条信息不存在，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            logger.info("根据ID查询电脑内存条信息成功，ID：{}", id);
            return Result.success(pcMemory);
        } catch (BusinessException e) {
            logger.warn("根据ID查询电脑内存条信息业务异常，ID：{}", id, e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("根据ID查询电脑内存条信息系统异常，ID：{}", id, e);
            return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.query.failed"));
        }
    }
    
    /**
     * 添加电脑内存条
     */
    @PostMapping
    @Operation(summary = "添加电脑内存条", description = "新增一条电脑内存条信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> addPcMemory(
            @Parameter(description = "电脑内存条信息", required = true) @RequestBody PcMemory pcMemory) {
        logger.info("添加电脑内存条请求，制造商：{}", pcMemory.getManufacturer());
        try {
            // 设置创建时间和更新时间
            pcMemory.setCreatedTime(new Date());
            pcMemory.setUpdatedTime(new Date());
            
            boolean result = pcMemoryService.save(pcMemory);
            if (result) {
                logger.info("添加电脑内存条成功，ID：{}", pcMemory.getId());
                return Result.success(true);
            } else {
                logger.warn("添加电脑内存条失败");
                return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.save.failed"));
            }
        } catch (Exception e) {
            logger.error("添加电脑内存条异常", e);
            return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.save.failed"));
        }
    }
    
    /**
     * 更新电脑内存条
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新电脑内存条", description = "根据ID更新电脑内存条信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "找不到记录", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> updatePcMemory(
            @Parameter(description = "电脑内存条ID", required = true) @PathVariable("id") Integer id,
            @Parameter(description = "电脑内存条信息", required = true) @RequestBody PcMemory pcMemory) {
        logger.info("更新电脑内存条请求，ID：{}", id);
        try {
            // 检查记录是否存在
            PcMemory existing = pcMemoryService.getById(id);
            if (existing == null) {
                logger.warn("更新电脑内存条信息不存在，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            
            // 设置ID和更新时间
            pcMemory.setId(id);
            pcMemory.setUpdatedTime(new Date());
            
            boolean result = pcMemoryService.updateById(pcMemory);
            if (result) {
                logger.info("更新电脑内存条成功，ID：{}", id);
                return Result.success(true);
            } else {
                logger.warn("更新电脑内存条失败，ID：{}", id);
                return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.update.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("更新电脑内存条业务异常，ID：{}", id, e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑内存条系统异常，ID：{}", id, e);
            return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.update.failed"));
        }
    }
    
    /**
     * 删除电脑内存条
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑内存条", description = "根据ID删除电脑内存条信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "找不到记录", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> deletePcMemory(
            @Parameter(description = "电脑内存条ID", required = true) @PathVariable("id") Long id) {
        logger.info("删除电脑内存条请求，ID：{}", id);
        try {
            // 检查记录是否存在
            PcMemory existing = pcMemoryService.getById(id);
            if (existing == null) {
                logger.warn("删除电脑内存条信息不存在，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            
            boolean result = pcMemoryService.removeById(id);
            if (result) {
                logger.info("删除电脑内存条成功，ID：{}", id);
                return Result.success(true);
            } else {
                logger.warn("删除电脑内存条失败，ID：{}", id);
                return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.delete.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("删除电脑内存条业务异常，ID：{}", id, e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑内存条系统异常，ID：{}", id, e);
            return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), MessageUtils.getMessage("common.delete.failed"));
        }
    }
    
}